import React, {Component} from 'react'
import {
  View,
  Text,
  TouchableOpacity,
  Platform,
  StyleSheet,
  ActivityIndicator,
  Image,
  ScrollView,
  RefreshControl, Clipboard, ImageBackground
} from 'react-native'
import {Actions} from "react-native-router-flux";
import font from './../../styles/font'
import colors from './../../styles/colors'
import ICON from 'react-native-vector-icons/Ionicons'
import ICON2 from 'react-native-vector-icons/FontAwesome'
import {List, ListItem} from 'react-native-elements'
import Toast2, {
  DURATION
} from 'react-native-easy-toast'
import {Toast, Overlay, Label, ListRow} from 'teaset'
import * as ShareMenu from './../common/ShareMenu'
import { SafeAreaView } from 'react-navigation';
import RNAlibcSdk, {AlibcTradeWebView} from 'react-native-alibc-sdk';
import {getUserId} from "../../services/token";

const PARAMS = {
  pid: "mm_108042659_0_0",
  forceH5: false,
  orders: {type: "orders",  payload: {orderType: 0, isAllOrder: true}},
};


const list = [
  {
    title:'我的订单',
    icon: 'meetup',
    key: 'order',
    iconColor:'#fec12b'
  },
  {
    title:'结算提现',
    icon: 'yen',
    key: 'price',
    iconColor:'#99cc01'
  },
  {
    title:'我的收藏',
    icon: 'star',
    key: 'collect',
    iconColor:'#fec12b'
  },
  {
    title:'浏览记录',
    icon: 'history',
    key: 'history',
    iconColor:'#99cc01'
  },
  {
    title:'赚钱疑问?',
    icon: 'question',
    key: 'help',
    iconColor:'#1ACCF9'
  },
  {
    title:'切换账号',
    icon: 'sign-out',
    key: 'signOut',
    iconColor:'#fec12b'
  }
]


const list2 = [
  {
    title:'帮助说明',
    icon: 'question',
    key: 'help',
    iconColor:'#1ACCF9'
  },
  {
    title:'切换账号',
    icon: 'sign-out',
    key: 'signOut',
    iconColor:'#fec12b'
  }
]
class DashboardScene extends Component{
  constructor(props){
    super(props)
    this.state = {
      isRefreshing: false
    }
  }

  static customKey = null;

  componentDidMount() {
    /* 初始化sdk(此方法为异步， 确保回调执行后再进行下一步操作)
     * 参数
     * pid: 绑定阿里妈妈帐号后在百川后台查询此帐号
     * forceH5：强制浏览器打开页面
     * callback: 回调函数
     */

    RNAlibcSdk.init(PARAMS.pid, PARAMS.forceH5, (err) => {
      if (!err)
        console.log("init taobao success")
      else
        console.log(err)
    });

    this.props.actions.userInfo()
  }

  componentWillReceiveProps(nextProps) {
    const {userInfo, userSign} = nextProps
    console.log(nextProps)
    if(nextProps.refresh){
      DashboardScene.customKey = Toast.show({
        text: '正在刷新',
        icon: <ActivityIndicator size='large'  />,
        position: 'center',
      });
    }

    if(nextProps.refresh && userInfo.isLoading === false){
      Actions.refresh({
        refresh: false
      });
      this.props.actions.userInfo()
    }


    if(this.props.userInfo !== userInfo){
      this.setState({isRefreshing: false});
      if (userInfo.error !== false) {
        Actions.login()
      }else{
        console.log(userInfo)
      }
    }

    if(this.props.userSign !== userSign){
     if(userSign.data){

       Clipboard.setString(global.default_kouling);
       if(userSign.data === '签到成功'){
         Overlay.show(<Overlay.PopView
           style={{alignItems: 'center', justifyContent: 'center'}}
           ref={v => this.signPopView = v}
         >
           <View style={{minWidth: 260, minHeight: 180, justifyContent: 'center', alignItems: 'center'}}>
             <Image source={{uri:'https://tao.vyxjj.com/build/images/sign.png'}} style={{width:350, height:350}}/>
             <ICON name="ios-close-circle-outline" color="#fff" size={35} onPress={()=>{
               this.signPopView && this.signPopView.close()}}/>
           </View>
         </Overlay.PopView>);
       }else{
         Toast.fail(userSign.data)
       }

     }
    }

  }


  showCustom() {
    if (DashboardScene.customKey) return;
    DashboardScene.customKey = Toast.show({
      text: '正在加载',
      icon: <ActivityIndicator size='large' color='#fff'/>,
      position: 'center',
    });
  }


  hideCustom() {
    if (!DashboardScene.customKey) return;
    Toast.hide(DashboardScene.customKey);
    DashboardScene.customKey = null;
  }

  _show(param) {
    RNAlibcSdk.show(param, (err, info) => {
        if (!err)
          console.log(info)
        else
          console.log(err)
      }
    );
  }

  _getUser() {
    RNAlibcSdk.getUser((err, userInfo) => {
        if (err)
          console.log(err);
        else
          console.log(userInfo)
      }
    );
  }

  _login() {
    // 唤起手淘app进行授权登录， 获取用户个人信息。
    RNAlibcSdk.login((err, userInfo) => {
        if (!err)
          console.log(userInfo)
        else
          console.log(err)
      }
    );
  }

  _onPress(key){
    switch (key){
      case 'taoTaoLogin':
        this._login()
        break;
        case 'order':
        Actions.UserOrder()
        break;
      case 'collect':
        Actions.UserCollect()
        break;
      case 'history':
        Actions.UserHistory()
        break;
      case 'help':
        Actions.webView({url:'https://tao.vyxjj.com/index/index/apphelp', title:'使用说明'})
        break;
      case 'price':
        Actions.UserPrice()
        break;
      case 'signOut':
        Actions.login()
        break;
      default:
        console.log(123);
    }
  }


  _onRefresh(){
    this.setState({isRefreshing: true});
    this.props.actions.userInfo()
  }

  content(data, meta, isLoading, error){
    if(!data && isLoading){
      return(
        <View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
          <Image source={require('./../../../assets/images/rolling.gif')} style={{width:230, height:230}}/>
        </View>
      )
    }

    if(error !== false){
      if(global.isWXAppInstalled){
      // if(true){
        return(
          <View style={{flex:1, justifyContent:'center', alignItems:'center', backgroundColor:'#fff'}}>
            <TouchableOpacity onPress={()=>{Actions.login()}}>
              <Text style={{color:'#000', fontSize:16}}>立即登录</Text>
            </TouchableOpacity>
          </View>
        )
      }else{

        return(
          <ScrollView style={styles.container}
                      refreshControl={
                        <RefreshControl
                          refreshing={this.state.isRefreshing}
                          onRefresh={this._onRefresh.bind(this)}
                          tintColor="#000"
                          title="正在刷新"
                          titleColor="#000"
                          colors={['#000']}
                          progressBackgroundColor="#fff"
                        />
                      }>
            <View style={styles.header}>
              <Image source={{uri:"https://tao.vyxjj.com/build/images/tx.jpg"}} style={styles.headIcon}/>
              <View style={styles.headerContent}>
                <Text style={[font.white14,{fontWeight:'bold'}]}>游客</Text>
              </View>
            </View>
            <View style={styles.search}>
              <TouchableOpacity style={styles.searchButton} onPress={()=>{
                Actions.lists({searchModal:true})
              }}>
                <ICON name="md-search" color='#9b9b9b' size={14} style={{marginRight:10}}/>
                <Text style={{color:'#9b9b9b', fontSize:14}}>快速查找产品</Text>
              </TouchableOpacity>
            </View>
            <TouchableOpacity style={styles.shareContainer} onPress={()=>{
              Overlay.show(ShareMenu.ShareMenu({
                'cate': 'help',
                'title': '发现极品-使用说明',
                'description': '领优惠券+返利+推荐返佣，真心比双11还便宜！',
                'thumbImage': 'http://tao.vyxjj.com/common/img/logo.png',
                'webpageUrl': 'https://tao.vyxjj.com/index/user/help',
              }))
            }}>
              <Text style={font.white14}>好东西要分享！ 分享赚积分</Text>
            </TouchableOpacity>
            <List containerStyle={{borderBottomColor:'#e5e5e5'}}>
              {
                list2.map((item, i) =>(
                  <ListItem
                    key={i}
                    title={item.title}
                    leftIcon={{name: item.icon, color:'#fff', type:'font-awesome', style:{
                        backgroundColor:item.iconColor,
                        fontSize:16,
                        borderRadius:11,
                        width:22,
                        height:22,
                        paddingTop:3,
                        paddingLeft: i === 1 || i === 4 ? 6 : 3
                      }}}
                    onPress={()=>{this._onPress(item.key)}}
                  />
                ))
              }
            </List>
          </ScrollView>
        )
      }

    }

    if(data){
      return(
        <ScrollView style={styles.container}
          refreshControl={
            <RefreshControl
              refreshing={this.state.isRefreshing}
              onRefresh={this._onRefresh.bind(this)}
              tintColor="#000"
              title="正在刷新"
              titleColor="#000"
              colors={['#000']}
              progressBackgroundColor="#fff"
            />
          }>
          <View style={styles.header}>
            <Image source={{uri:data.avatar}} style={styles.headIcon}/>
            <View style={styles.level}><Text style={{ fontSize:13, color:'#e12f32',}}>{meta.levelName}</Text></View>
            <TouchableOpacity style={styles.headerContent} onPress={()=>{Actions.UserDate({...data})}} activeOpacity={1}>
              <Text style={[font.white16,{fontWeight:'bold', marginBottom:5}]}>{data.username} <ICON name="md-create" color='#fff' size={18}/></Text>
              <Text style={[font.white15]}>{data.province}-{data.city}</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.signIn} onPress={()=>{this.props.actions.userSign()}} activeOpacity={1}>
              <Text style={{color: '#ff9518', margin:5}}>每日签到</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.search}>
            <TouchableOpacity style={styles.searchButton} onPress={()=>{
              Actions.lists({searchModal:true})
            }} activeOpacity={1}>
              <ICON name="md-search" color='#ccc' size={16} style={{marginRight:10}}/>
              <Text style={{color:'#ccc'}}>快速查找产品</Text>
            </TouchableOpacity>
          </View>
          {global.isWXAppInstalled ? <TouchableOpacity style={styles.shareContainer} onPress={()=>{
            Overlay.show(ShareMenu.ShareMenu({
              'cate': 'help',
              'title': '发现极品-使用说明',
              'description': '领优惠券+返利+推荐返佣，真心比双11还便宜！',
              'thumbImage': 'http://tao.vyxjj.com/common/img/logo.png',
              'webpageUrl': 'https://tao.vyxjj.com/index/user/help?shareid='+getUserId(),
            }))
          }}>
            <Text style={{ color:'#fff', fontSize:18,}}>好东西要分享！ 分享赚积分</Text>
          </TouchableOpacity> : null}

          <View style={styles.jifenContainer}>
            <TouchableOpacity style={[styles.modal, {borderRightColor:'#d9d9d9', borderRightWidth:0.3}]} onPress={()=>{
              // Actions.jump('index', {refresh:true})
              Actions.UserOrder()
            }} activeOpacity={1}>
              <ICON2 name="rmb" size={28} color="#E12F32" style={{marginBottom: 10}}/>
              <Text style={{ color:'#000', fontSize:14,}}>预估收入:{meta.price}元</Text>
            </TouchableOpacity>
            <TouchableOpacity style={[styles.modal, {borderRightColor:'#d9d9d9', borderRightWidth:0.3}]} onPress={()=>{
              Actions.UserChats()
            }} activeOpacity={1}>
              <ICON2 name="meetup" size={28} color="#E12F32" style={{marginBottom: 10}}/>
              <Text style={{ color:'#000', fontSize:14,}}>积分:{data.jifen}分</Text>
            </TouchableOpacity>
            <TouchableOpacity style={[styles.modal,]} onPress={()=>{
              Actions.UserShare()
            }} activeOpacity={1}>
              <ICON2 name="users" size={23} color="#E12F32" style={{marginBottom: 10}}/>
              <Text style={{ color:'#000', fontSize:14,}}>推荐:{meta.shareCount}人</Text>
            </TouchableOpacity>
          </View>
          <List containerStyle={{borderBottomColor:'#e5e5e5', borderTopColor:'#e5e5e5', marginBottom:10}}>
            {
              list.map((item, i) =>{

                if(global.isWXAppInstalled){
                  return (
                    <ListRow
                      key={i}
                      title={item.title}
                      icon={
                        <View style={{backgroundColor:item.iconColor, borderRadius:23, width:25, height:25, marginRight:10,justifyContent:'center', alignItems:'center'}}>
                          <ICON2 name={item.icon} size={14} color="#fff"/>
                        </View>
                      }
                      onPress={()=>{this._onPress(item.key)}}
                    />
                  )
                }else if(!global.isWXAppInstalled && i !== 4){
                  return (
                    <ListRow
                      key={i}
                      title={item.title}
                      icon={
                        <View style={{backgroundColor:item.iconColor, borderRadius:23, width:25, height:25, marginRight:10,justifyContent:'center', alignItems:'center'}}>
                          <ICON2 name={item.icon} size={14} color="#fff"/>
                        </View>
                      }
                      onPress={()=>{this._onPress(item.key)}}
                    />
                  )
                }

              })
            }
          </List>

          <View style={{marginLeft: 10, width:120, borderBottomColor:'#e64340', borderBottomWidth:0.3, paddingBottom: 8, marginBottom:5}}>
            <Text style={{color:'#e64340', fontSize:16}}>月收入龙虎榜</Text>
          </View>
          <View style={{borderTopColor:'#e5e5e5', paddingLeft:15,  backgroundColor:'#fff'}}>
            <View style={styles.paiItem}>
              <Text style={styles.paiItemText}>排名</Text>
              <Text style={[styles.paiItemText, {flex:1}]}>昵称</Text>
              <Text style={[styles.paiItemText, {flex:1}]}>收入(￥)</Text>
            </View>

            {this.props.userInfo.meta.top_user.map(function (item, i) {
              let level = i + 1
              return (
                <View style={[styles.paiItem]} key={i}>
                  {level <= 3 ?
                    <ImageBackground style={{width:30, height:30, alignItems:'center'}} resizeMode='contain' source={{uri:'http://tao.vyxjj.com/static/user/images/top1.png'}}>
                      <Text style={[styles.paiItemText, styles.levelThree]}>{level}</Text>
                    </ImageBackground>
                    :
                    <Text style={[styles.paiItemText, {width:30}]}>{level}</Text>
                  }

                  <Text style={[styles.paiItemText, {flex:1}]}>{item.username}</Text>
                  <Text style={[styles.paiItemText, {flex:1}]}>{item.jine}</Text>
                </View>
              )
            })}
            <View style={styles.paiItem}>
              <Text style={styles.paiItemText}>. . . . .</Text>
            </View>
            <View style={styles.paiItem}>
              <Text style={styles.paiItemText}>{this.props.userInfo.meta.user_order.order}</Text>
              <Text style={[styles.paiItemText, {flex:1}]}>{this.props.userInfo.meta.user_order.name}</Text>
              <Text style={[styles.paiItemText, {flex:1}]}>{this.props.userInfo.meta.user_order.jifen}</Text>
            </View>
          </View>

        </ScrollView>
      )
    }
  }



  render(){
    const {data, meta, isLoading, error} = this.props.userInfo
    return(
      <SafeAreaView style={styles.container}>
        {this.content(data, meta, isLoading, error)}
        <Toast2
          ref={view => this.toast = view}
          style={{backgroundColor:'red'}}
          opacity={0.6}
          position='top'/>
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container:{
    flex: 1,
    backgroundColor:'#f3f5f7'
  },
  header:{
    height: Platform.OS === 'ios' ? 90 : 70,
    backgroundColor: '#E12F32',
    paddingHorizontal:30,
    paddingVertical:18,
    flexDirection:'row',
    alignItems:'center',
    position:'relative',
    marginBottom:10
  },
  headIcon:{
    width:55,
    height:55,
    borderRadius:28,
  },
  headerContent:{
    marginLeft:15,
    flex:1,
  },
  signIn:{
    width:80,
    backgroundColor:'#fff',
    borderRadius:50,
    justifyContent:'center',
    alignItems:'center'
  },
  search:{
    backgroundColor:'#f3f5f7',
    height:40,
    paddingHorizontal:8,
    borderBottomWidth:0.3,
    borderBottomColor:'#d7d6dc'
  },
  searchButton:{
    backgroundColor:'#fff',
    flex:1,
    borderRadius:5,
    justifyContent:'center',
    alignItems:'center',
    height:30,
    flexDirection:'row',
    borderColor:'#f3f5f7',
    borderWidth:0.3,
    marginBottom:10
  },
  jifenContainer:{
    paddingVertical:8,
    paddingHorizontal:2,
    height:60,
    flexDirection:'row',
    justifyContent:'space-around',
    marginBottom:20
  },
  modal:{
    height:80,
    justifyContent:'center',
    alignItems:'center',
    flex:1,
    borderTopWidth: 0.3,
    borderBottomWidth: 0.3,
    borderTopColor: '#d9d9d9',
    borderBottomColor: '#d9d9d9',
    backgroundColor:'#fff',
  },
  shareContainer:{
    marginTop:10,
    marginHorizontal:5,
    height:50,
    justifyContent:'center',
    alignItems:'center',
    backgroundColor:'#ff9518',
    marginBottom:10,
  },
  level:{
    position: 'absolute',
    left: 60,
    top:40,
    opacity: .85,
    width:30,
    height:30,
    borderWidth:0.5,
    borderColor: '#e12f32',
    backgroundColor: '#fff',
    zIndex: 10,
    borderRadius:20,
    flex:1,
    justifyContent:'center',
    alignItems:'center'
  },
  paiItem:{
    flex:1,
    borderBottomColor:'#e5e5e5',
    borderBottomWidth:0.3,
    flexDirection:'row',
    justifyContent:'space-around',
    alignItems:'center',
    height:50,
    // backgroundColor:'#fff',
  },
  paiItemText:{
    fontSize:15,
    color:'#000',
    textAlign: 'center',
  },
  levelThree:{
    color:'#fff'
  }

})

export const LayoutComponent = DashboardScene

export function mapStateToProps(state, props) {
  return {
    routes: state.routes,
    userInfo: state.userInfoReducer,
    userSign: state.userSignReducer
  }
}